Class Notes 30/09/2025 — While loops, For loops & Iterables

Try me

Open In ColabBinder

2) while Loops

Definition: Repeat a block while a condition remains True. Syntax:

while condition:
    # loop body
    # executed while the condition is True
    # condition is re-evaluated each iteration

Important

  • Ensure the loop eventually stops (update variables, read input, etc.).

  • Use break to exit early; continue to skip to next iteration.

[ ]:
# Example: echo until user types 'quit' (safe sentinel pattern)
while True:
    msg = input("Say something ('quit' to stop): ")
    if msg.strip().lower() == "quit":
        break                 # exit the loop
    if not msg:               # empty input? skip
        continue
    print("You said:", msg)
print("Bye!")

``break`` / ``continue`` demo

[ ]:
x = 0
y = 0
while x < 5:
    x += 1
    if x % 2 == 0:        # even
        print(x, "is even")
        continue          # go to next iteration (skip y += x)
    y += x                # odd: accumulate
print("Sum of odd numbers 1..5 is", y)
[ ]:

3) Iterables: Lists

Definition: Ordered, indexable, mutable collection. Create: lst = [a, b, c] • Empty: [] • Length: len(lst) Indexing: lst[i] (0-based) • Negative index from end: lst[-1]

Common ops: append, pop, insert, remove, in, count

[ ]:
row = ["A", "B", "C"]
print(len(row), row[0], row[-1])  # 3 A C
row.append("D")
print(row)   # ["A", "B", "C", D]

3.1 Slicing

  • Syntax: seq[start:stop:step] slices seq from start to stop with step (stop excluded)

  • Omitted parts default to start, step 1, or end of the sequence.

  • Use negative step to go backwards

[ ]:
s = ["A","B","C","D","E","F"]
print(s[1:4])     # ['B','C','D']
print(s[:3])      # first three
print(s[3:])      # from index 3 to end
print(s[::2])     # every 2nd
print(s[::-1])    # reversed copy

4) for Loops

Definition: Iterate over the elements of an iterable. Syntax:

for element in iterable:
    # use element

Tips

  • Use for name in names: to get items; use enumerate(iterable) when you also need the index.

  • continue and break work as in while loops.

Grasping the concept: Iteration

Real‑world example: corporate emails

Let us write a hand-made email generator. Each student in the first row, given their full name, should write in the whiteboard an email with the following format: Rule: first initial + surname (lowercase, no spaces/hyphens) + @stark_company.com

[ ]:

names = ["Tony Stark", "Bruce Banner", "Thor Odinson"] for full in names: print(full) #prints names in different lines for i, full in enumerate(names, start=1): print(i, full)

4.1 Range

The range function is a built-in function widely used in combination with for loops.

  • Use range(n) to loop a specific number of times.

  • Use `range(start,stop,step) as in slicing to generate a specific numeric sequence

for i in range(5):

[ ]:
for i in range(5):
    print(i)        # prints 0, 1, 2, 3, 4

for i in range(1,7,2):
    print(i)        # prints (1, 3, 5)

5) Quick Checks (self‑test)

  1. What does this print and why?

x = 20
if x < 20:
    msg = "A"
elif x <= 20:
    msg = "B"
else:
    msg = "C"
print(msg)
  1. Write a loop that sums only the even numbers in nums = [0,1,2,3,4,5].

  2. Slice letters = list("ABCDEFG") to get ["C","D","E"].

  3. Turn the rule “age between 18 and 64 inclusive” into a single boolean expression.

  4. Try writing the corporate email generator from the example above.